/**
 * editor.md 图片粘贴上传插件
 */
(function () {

    var factory = function (exports) {
        var $ = jQuery;
        var pluginName = "image-handle-paste";  // 定义插件名称

        //图片粘贴上传方法
        exports.fn.imagePaste = function () {
            var _this = this;
            var cm = _this.cm;
            var settings = _this.settings;
            var editor = _this.editor;
            var classPrefix = _this.classPrefix;
            var id = _this.id;

            if (!settings.imageUpload || !settings.imageUploadURL) {
                console.log('你还未开启图片上传或者没有配置上传地址');
                return false;
            }

            //监听粘贴板事件
            $('#' + id).on('paste', function (e) {

                var items = (e.clipboardData || e.originalEvent.clipboardData || window.clipboardData).items;
                if (items.length === 0) {
                    return
                }

                let entry;
                let isImgFile;
                var forms = new FormData(document.forms[0]);
                for (var i = 0; i < items.length; i++) {
                    if (items[i].kind !== "file") {
                        continue
                    }

                    var file = items[i].getAsFile();
                    var fileName = ""
                    entry = items[i].webkitGetAsEntry();
                    isImgFile = false
                    if (entry && entry.name !== "") {
                        fileName = entry.name;
                    } else {
                        if (items[i].type.indexOf('image') > -1) {
                            fileName = "imgFile_" + Date.parse(new Date()) + ".png";
                            isImgFile = true
                        } else {
                            fileName = ""
                        }
                    }

                    if (fileName === "") {
                        continue;
                    }

                    forms.append(classPrefix + "file[" + i + "]", file, fileName);
                }

                _ajax(settings.imageUploadURL, forms, function (ret) {
                    if (ret.code == 0 && ret.data && ret.data.files && ret.data.files.length > 0) {
                        for (m = 0; m < ret.data.files.length; m++) {
                            file = ret.data.files[m]
                            if (file.fileIsImg) {
                                cm.replaceSelection("![" + (file.fileName) + "](" + file.url + ")\n");
                            } else {
                                cm.replaceSelection("[" + (file.fileName) + "](" + file.url + ")\n");
                            }
                        }
                    }
                    console.log(ret);
                })

                /*
                //判断图片类型
                if (items && items[0].type.indexOf('image') > -1) {

                    var file = items[0].getAsFile();

                    // 创建FormData对象进行ajax上传
                    var forms = new FormData(document.forms[0]); //Filename
                    forms.append(classPrefix + "image-file", file, "imgFile_" + Date.parse(new Date()) + ".png"); // 文件

                    // imageDialog弹窗
                    // _this.executePlugin("imageDialog", "image-dialog/image-dialog");

                    _ajax(settings.imageUploadURL, forms, function (ret) {
                        if (ret.code == 0 && ret.data && ret.data.url != "") {
                            //$("." + classPrefix + "image-dialog").find("input[data-url]").val(ret.url);
                            cm.replaceSelection("![粘贴图片](" + ret.data.url + ")");
                        }
                        console.log(ret.message);
                    })
                }
                */
            })
        };
        // ajax上传图片 可自行处理
        var _ajax = function (url, data, callback) {
            $.ajax({
                "type": 'post',
                "cache": false,
                "url": url,
                "data": data,
                "dateType": "json",
                "processData": false,
                "contentType": false,
                "mimeType": "multipart/form-data",
                success: function (ret) {
                    callback(JSON.parse(ret));
                },
                error: function (err) {
                    console.log('请求失败')
                }
            })
        }
    };

    // CommonJS/Node.js
    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
        module.exports = factory;
    } else if (typeof define === "function") {  // AMD/CMD/Sea.js
        if (define.amd) { // for Require.js
            define(["editormd"], function (editormd) {
                factory(editormd);
            });
        } else { // for Sea.js
            define(function (require) {
                var editormd = require("./../../editormd");
                factory(editormd);
            });
        }
    } else {
        factory(window.editormd);
    }

})();
